package jk.zmn.thread.syn;

/**
 * @author 张梦楠
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2018/5/2617:28
 * @blog www.itzmn.com
 *
 *  单例模式
 *      饿汉模式
 *      懒汉模式
 *          创建一个静态对象，调用静态方法，实现懒加载
 *      双重检查
 */
public class JvmSingleDemo {

     public static void main(String[] args) {
         JvmThread jvmThread = new JvmThread(200);
         JvmThread jvmThread2 = new JvmThread(200);
         jvmThread.start();
         jvmThread2.start();
     }


}
class Jvm{
    private static Jvm jvm= null;

    private Jvm() {

    }
    public static Jvm getinstances1(long time)  {

        if (jvm == null){
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            jvm = new Jvm();
        }
        return jvm;

    }
    public static synchronized Jvm getinstances2(long time)  {

        if (jvm == null){
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            jvm = new Jvm();
        }
        return jvm;
    }
    public static Jvm getinstances3(long time)  {
        synchronized (Jvm.class) {
            if (jvm == null) {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                jvm = new Jvm();
            }
            return jvm;
        }
    }

    /**
     * 双重判断
     * @param time
     * @return
     */
    public static Jvm getinstances(long time)  {
        if (jvm == null) {
            synchronized (Jvm.class) {
                if (jvm == null) {
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    jvm = new Jvm();
                }
            }
        }
        return jvm;
    }
}

class JvmThread extends Thread{
    private long time;
    public JvmThread(long time){
        this.time = time;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"创建了"+Jvm.getinstances(time));
    }
}